import xml.dom.minidom
from xml.dom.minidom import Node

import string
from string import *

class XMLNode:
    def __init__(self, name):
        self._name = name
        self._children = []
        self._text=[]
        self._parent = None
        
    def _textblock(self):
        return "\n".join(self._text)
    
    def __str__(self, spc=''):
        out = '\n' + spc + '<-- ' + self._name
        for i in dir(self):
            if i[0] != '_':
                out += "\n" + spc + "|  " + str(i) + ": " + str(getattr(self, i))
        for i in self._text:
            out += "\n" + spc + "|  " + i
        for i in self._children:
            if i is not None: #for full compatability with storycrumbs, this check must occur. I don't remember why.
                out += i.__str__(spc + '|  ')
        out += "\n" + spc + "--/>"
        return out

def parseXML(node):
    n = XMLNode(node.tagName)
    for i in range(0, node.attributes.length):
        a = node.attributes.item(i)
        setattr(n, a.nodeName, a.nodeValue)
        
    for child in node.childNodes:
        #Add real child elements
        if child.nodeType == Node.ELEMENT_NODE:
            newc = parseXML(child)
            n._children.append(newc)
            newc._parent = n
                
        #Add text elements
        if child.nodeType == Node.TEXT_NODE:
            text = child.data
            text = text.rstrip().lstrip()
            textlines = text.split("\n")
            for line in textlines:
                if len(line) > 0:
                    n._text.append(line.rstrip().lstrip())
    return n
        
def cleanXML(node):
    mylist = node.childNodes
    
    #remove comments
    for n in mylist:
        if n.nodeType == Node.COMMENT_NODE:
            mylist.remove(n)
        else:
            cleanXML(n)
    mylist = node.childNodes     
    #remove empty text elements   
    for n in mylist:
        if n.nodeType == Node.TEXT_NODE:
            if len(n.data.split()) == 0:
                mylist.remove(n)
        else:
            cleanXML(n)
            
def getXML(filename):
    doc = xml.dom.minidom.parse(filename)
    cleanXML(doc)
    return doc